<?php
namespace Modules\Queue\Library;

use Core\Mvc\Entity\EntityInterface;
use Phalcon\Events\Event;

class EntityListener
{
    protected $_imagesToLocalQueue = [];

    protected function getImage($content, $maxNum, $order = 'ALL')
    {
        $pattern = "/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg|\.bmp]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern, $content, $match);
        if (isset($match[1]) && !empty($match[1])) {
            if ($order === 'ALL') {
                return array_slice($match[1], 0, $maxNum);
            }
            if (is_numeric($order) && isset($match[1][$order])) {
                return $match[1][$order];
            }
        }
        return false;
    }

    public function saveBefore(Event $event, EntityInterface $entity)
    {
        if ($entity->getEntity() == 'node') {
            $field = formFieldInit($entity->getField());
            foreach ($field as $key => $element) {
                if (isset($entity->{$key}) && isset($element['imagesToLocal']) && $element['imagesToLocal'] == true) {
                    $output = ImagesToLocal::to($entity->{$key});
                    $entity->{$key} = $output['body'];
                    $this->_imagesToLocalQueue += $output['queue'];
                }
            }
            //print_r($entity->images);
            foreach ($field as $key => $element) {
                if (is_array($element) && isset($element['autoThumbnail']) && isset($entity->{$key}) && empty($entity->{$key}) && isset($entity->{$element['autoThumbnail']['name']}) && !empty($entity->{$element['autoThumbnail']['name']})) {
                    if (!isset($element['autoThumbnail']['order'])) {
                        $element['autoThumbnail']['order'] = 'ALL';
                    }
                    $value = $this->getImage($entity->{$element['autoThumbnail']['name']}, $element['autoThumbnail']['number'], $element['autoThumbnail']['order']);
                    if ($value) {
                        if (isset($element['autoThumbnail']['type']) && $element['autoThumbnail']['type'] == 'string') {
                            $entity->{$key} = implode(';', $value);
                        } else {
                            $entity->{$key} = $value;
                        }
                    }
                }
            }
        }
    }

    public function saveAfter(Event $event, EntityInterface $entity)
    {
        if ($this->_imagesToLocalQueue && !empty($this->_imagesToLocalQueue)) {
            $queue = new Queue();
            $queue->add('imgToLocal', $this->_imagesToLocalQueue);
        }
    }
}